const Base = require('./base.js');
const qiniu = require('qiniu');
module.exports = class extends Base {
  // 查询视频列表
  async indexAction() {
    const model = this.model('video')
      .alias('vd')
      .field([
        'vd.*',
        'g.name',
        'g.primary_pic_url',
        'g.retail_price',
        'g.promotion_price',
        'g.list_pic_url'
      ])
      .join({
        table: 'goods',
        join: 'inner',
        as: 'g',
        on: ['goods_id', 'id']
      })
      .where({
        'vd.isonline': 1,
        'vd.is_review': 1,
        'vd.class':
          this.get('class') == 0
            ? ['IN', [1, 2, 3, 4, 5, 6]]
            : this.get('class')
      })
      .order(['create_time DESC'])
      .page(this.get('page'))
      .limit(20);
    const videolist = await model.countSelect();
    return this.success(videolist);
  }
  // 添加视频信息
  async addAction() {
    const videodetal = this.post('videodetail');
    Object.assign(videodetal, {
      trackid: this.model('order').generateOrderNumber(),
      create_time: this.getTime(),
      user_id: this.getLoginUserId()
    });
    const videoid = await this.model('video').add(videodetal);
    if (!videoid) {
      return this.fail('添加视频失败');
    }
    return this.success({ videoid: videoid });
  }
  async updownAction() {
    const videoid = await this.model('video')
      .where({ id: this.post('id'), user_id: this.getLoginUserId() })
      .delete();
    if (videoid == 0) {
      return this.fail('删除视频失败');
    }
    return this.success(videoid);
  }
  async tokenAction() {
    const accessKey = '2P9mo_mKokDxr-9lg65FfEP1ehU02bcbH1AwgEh6';
    const secretKey = 'B9mbuVV6FSkXUqF-cHr0sV7fX3mBy6s5WngEG6qf';
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    const options = {
      scope: 'danghongfang'
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
    return this.success(uploadToken);
  }
  // 记录浏览量
  async viewAction() {
    const item = this.post('item');
    await this.model('video')
      .where({ id: item.id })
      .increment('view', 1);
  }
  async switchAction() {
    const result = await this.model('config').select();
    return this.success(result);
  }
};
